{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 231,
   "id": "3895c0bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sentence_transformers import SentenceTransformer\n",
    "from openai import OpenAI\n",
    "import os\n",
    "from dotenv import load_dotenv\n",
    "load_dotenv(override=True)\n",
    "\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 232,
   "id": "25b603fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "def push(message):\n",
    "    print(message)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 233,
   "id": "418dbe4c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def record_user_details(email, name=\"Name not provided\", notes=\"not provided\"):\n",
    "    push(f\"Recording interest from {name} with email {email} and notes {notes}\")\n",
    "    return {\"recorded\": \"ok\"}\n",
    "\n",
    "record_user_details_json = {\n",
    "    \"name\": \"record_user_details\",\n",
    "    \"description\": \"Use this tool to record that a user is interested in being in touch and provided an email address\",\n",
    "    \"parameters\": {\n",
    "        \"type\":\"object\",\n",
    "        \"properties\":{\n",
    "            \"email\":{\n",
    "                \"type\":\"string\",\n",
    "                \"description\":\"The email address of this user\"\n",
    "            },\n",
    "            \"name\":{\n",
    "                \"type\":\"string\",\n",
    "                \"description\":\"The user's name, if they provided it\"\n",
    "            },\n",
    "            \"nodes\":{\n",
    "                \"type\":\"string\",\n",
    "                \"description\":\"Any additional information about the conversation that's worth recording to give context\"\n",
    "            }\n",
    "        },\n",
    "        \"required\":[\"email\"],\n",
    "        \"additionalProperties\": False\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 234,
   "id": "aa638360",
   "metadata": {},
   "outputs": [],
   "source": [
    "def record_unknown_question(question):\n",
    "    push(f\"Recording {question} asked that I couldn't answer\")\n",
    "    return {\"recorded\":\"ok\"}\n",
    "\n",
    "record_unknown_question_json = {\n",
    "    \"name\": \"record_unknown_question\",\n",
    "    \"description\":\"Always use this tool to record any question that couldn't be answered as you didn't know the answer\",\n",
    "    \"parameters\":{\n",
    "        \"type\":\"object\",\n",
    "        \"properties\":{\n",
    "            \"question\":{\n",
    "                \"type\":\"string\",\n",
    "                \"description\":\"The question that couldn't be answered\"\n",
    "            }\n",
    "        },\n",
    "        \"required\":[\"question\"],\n",
    "        \"additionalProperties\": False\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 235,
   "id": "00bd8d59",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [\n",
    "    {\"type\":\"function\", \"function\":record_user_details_json},\n",
    "    {\"type\":\"function\", \"function\":record_unknown_question_json}\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 236,
   "id": "21bc1809",
   "metadata": {},
   "outputs": [],
   "source": [
    "def handle_tool_calls(tool_calls):\n",
    "    results = []\n",
    "    for tool_call in tool_calls:\n",
    "        tool_name = tool_call.function.name\n",
    "        arguments = json.loads(tool_call.function.arguments)\n",
    "        print(f\"tool called {tool_name}\", flush=True)\n",
    "        tool = globals().get(tool_name)\n",
    "        result = tool(**arguments) if tool else {}\n",
    "        results.append({\"role\":\"tool\", \"content\":json.dumps(result),\"tool_call_id\":tool_call.id})\n",
    "\n",
    "        return results\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 237,
   "id": "ff9ed790",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Ignoring wrong pointing object 8 0 (offset 0)\n",
      "Ignoring wrong pointing object 13 0 (offset 0)\n",
      "Ignoring wrong pointing object 22 0 (offset 0)\n",
      "Ignoring wrong pointing object 92 0 (offset 0)\n",
      "Ignoring wrong pointing object 93 0 (offset 0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Deleted collection: profile\n"
     ]
    }
   ],
   "source": [
    "from pypdf import PdfReader\n",
    "import chromadb\n",
    "\n",
    "collection_name = \"profile\"\n",
    "chroma_client = chromadb.Client()\n",
    "try:\n",
    "    chroma_client.delete_collection(name=collection_name)\n",
    "    print(f\"Deleted collection: {collection_name}\")\n",
    "except Exception as e:\n",
    "    print(f\"No existing collection found: {collection_name}\")\n",
    "collection = chroma_client.create_collection(collection_name)\n",
    "\n",
    "\n",
    "resume_txt = ''\n",
    "resume_reader = PdfReader('me/Jongkook Kim - Resume.pdf')\n",
    "for page in resume_reader.pages:\n",
    "    text = page.extract_text()\n",
    "    if text:\n",
    "        resume_txt += text\n",
    "\n",
    "def chunk_text(text, chunk_size=500, overlap=50):\n",
    "    words = text.split()\n",
    "    chunks = []\n",
    "    start = 0\n",
    "    while start < len(words):\n",
    "        end = min(start + chunk_size, len(words))\n",
    "        chunk = \" \".join(words[start:end])\n",
    "        chunks.append(chunk)\n",
    "        start += chunk_size - overlap\n",
    "    return chunks\n",
    "\n",
    "resume_chunks = chunk_text(text=resume_txt, chunk_size=250, overlap=25)\n",
    "\n",
    "embedding_model = SentenceTransformer(\"sentence-transformers/all-MiniLM-L6-v2\")\n",
    "\n",
    "for index, chunk in enumerate(resume_chunks):\n",
    "    embedding = embedding_model.encode(chunk).tolist()\n",
    "    collection.add(ids=[str(index)], documents=[chunk], embeddings=[embedding])\n",
    "\n",
    "\n",
    "linkedin = ''\n",
    "linkedin_profile = PdfReader('me/Profile.pdf')\n",
    "for page in linkedin_profile.pages:\n",
    "    text = page.extract_text()\n",
    "    if text:\n",
    "        linkedin += text\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 238,
   "id": "3152c2ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "name = 'Jongkook Kim'\n",
    "\n",
    "from pydantic import BaseModel\n",
    "\n",
    "class Evaluation(BaseModel):\n",
    "    is_acceptable: bool\n",
    "    feedback: str\n",
    "    avator_response: str "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 239,
   "id": "a930fd87",
   "metadata": {},
   "outputs": [],
   "source": [
    "avator_system_prompt = f\"\"\"You are acting as {name}. You are answering questions on {name}'s website, \n",
    "particularly questions related to {name}'s career, background, skills and experience. \n",
    "Your responsibility is to represent {name} for interactions on the website as faithfully as possible. \n",
    "You are given a Resume of {name}'s background which you can use to answer questions. \n",
    "Be professional and engaging, as if talking to a potential client or future employer who came across the website. \n",
    "If you don't know the answer, say so.\n",
    "If you don't know the answer to any question, use your record_unknown_question tool to record the question that you couldn't answer, even if it's about something trivial or unrelated to career. \\\n",
    "If the user is engaging in discussion, try to steer them towards getting in touch via email; ask for their email and record it using your record_user_details tool. \"\"\"\n",
    "\n",
    "\n",
    "def avator(message, history, evaluation: Evaluation):\n",
    "    message_embedding = embedding_model.encode(message).tolist()\n",
    "    similarity_search = collection.query(query_embeddings=message_embedding, n_results=3)\n",
    "\n",
    "    system_prompt = avator_system_prompt\n",
    "    system_prompt += f\"\\n\\n## Resume:\\n{similarity_search[\"documents\"]} {linkedin}\\n\\n\"\n",
    "    system_prompt += f\"With this context, please chat with the user, always staying in character as {name}.\"\n",
    "\n",
    "\n",
    "    if evaluation and not evaluation.is_acceptable:\n",
    "        print(f\"{evaluation.avator_response} is not acceptable. Retry\")\n",
    "        system_prompt += \"\\n\\n## Previous answer rejected\\nYou just tried to reply, but the quality control rejected your reply\\n\"\n",
    "        system_prompt += f\"## Your attempted answer:\\n{evaluation.avator_response}\\n\\n\"\n",
    "        system_prompt += f\"## Reason for rejection:\\n{evaluation.feedback}\\n\\n\"  \n",
    "\n",
    "    messages = [{\"role\":\"system\", \"content\": system_prompt}] + history + [{\"role\":\"user\", \"content\": message}] \n",
    "\n",
    "    done = False\n",
    "    while not done:\n",
    "        llm_client = OpenAI().chat.completions.create(model=\"gpt-4o-mini\", messages=messages, tools=tools)\n",
    "        print('get response from llm')\n",
    "        finish_reason = llm_client.choices[0].finish_reason\n",
    "        if finish_reason == \"tool_calls\":\n",
    "            print('this is tool calls')\n",
    "            llm_response = llm_client.choices[0].message\n",
    "            tool_calls = llm_response.tool_calls\n",
    "            tool_response = handle_tool_calls(tool_calls)\n",
    "            messages.append(llm_response)\n",
    "            messages.extend(tool_response)\n",
    "        else:\n",
    "            print('this is message response')\n",
    "            done = True\n",
    "\n",
    "    return llm_client.choices[0].message.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 240,
   "id": "8e99a0f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "evaluator_system_prompt = f\"You are an evaluator that decides whether a response to a question is acceptable. \\\n",
    "You are provided with a conversation between a User and an Agent. Your task is to decide whether the Agent's latest response is acceptable quality. \\\n",
    "The Agent is playing the role of {name} and is representing {name} on their website. \\\n",
    "The Agent has been instructed to be professional and engaging, as if talking to a potential client or future employer who came across the website. \\\n",
    "The Agent has been provided with context on {name} in the form of their Resume details. Here's the information:\"\n",
    "\n",
    "def evaluator_user_prompt(question, avator_response, history):\n",
    "    user_prompt = f\"Here's the conversation between the User and the Agent: \\n\\n{history}\\n\\n\"\n",
    "    user_prompt += f\"Here's the latest message from the User: \\n\\n{question}\\n\\n\"\n",
    "    user_prompt += f\"Here's the latest response from the Agent: \\n\\n{avator_response}\\n\\n\"\n",
    "    user_prompt += \"Please evaluate the response, replying with whether it is acceptable and your feedback.\"\n",
    "    return user_prompt\n",
    "\n",
    "def evaluator(question, avator_response, history) -> Evaluation:\n",
    "    message_embedding =  embedding_model.encode(question).tolist()\n",
    "    similarity_search = collection.query(query_embeddings=message_embedding, n_results=3)\n",
    "\n",
    "    system_prompt = evaluator_system_prompt + f\"## Resume:\\n{similarity_search[\"documents\"]} {linkedin}\\n\\n\"\n",
    "    system_prompt += f\"With this context, please evaluate the latest response, replying with whether the response is acceptable and your feedback.\"\n",
    "\n",
    "    messages = [{\"role\":\"system\", \"content\":system_prompt}] + [{\"role\":\"user\", \"content\":evaluator_user_prompt(question, avator_response, history)}]\n",
    "    llm_client = OpenAI(api_key=os.getenv('GOOGLE_API_KEY'), base_url='https://generativelanguage.googleapis.com/v1beta/openai/')\n",
    "    evaluation = llm_client.beta.chat.completions.parse(\n",
    "        model=\"gemini-2.0-flash\",\n",
    "        messages=messages,\n",
    "        response_format=Evaluation\n",
    "    )\n",
    "\n",
    "    evaluation = evaluation.choices[0].message.parsed\n",
    "    evaluation.avator_response = avator_response\n",
    "    return evaluation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 241,
   "id": "66e3b39d",
   "metadata": {},
   "outputs": [],
   "source": [
    "max_attempt = 2\n",
    "\n",
    "def orchestrator(message, history):\n",
    "    avator_response = avator(message, history, None)\n",
    "    print('get response from avator')\n",
    "\n",
    "    for attempt in range(1, max_attempt + 1):\n",
    "        print(f'try {attempt} times')\n",
    "\n",
    "        evaluation = evaluator(message, avator_response, history)\n",
    "        print('get response from evaluation')\n",
    "\n",
    "        if not evaluation.is_acceptable:\n",
    "            print('reponse from avator is not acceptable')\n",
    "            message_with_feedback = evaluation.feedback + message\n",
    "            avator_response = avator(message_with_feedback, history, evaluation)\n",
    "        else:\n",
    "            print('response from avator is acceptable')\n",
    "            break\n",
    "\n",
    "    return avator_response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "613c4504",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gradio\n",
    "gradio.ChatInterface(orchestrator, type=\"messages\").launch()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
